include ApplicationHelper
include ContactsHelper

class ContactUsController < ApplicationController
  prepend_before_filter :authenticate_user!, :only => []
  before_filter :validate_data, :except => [:index]

  #guardo la ultima url visitada del controller mientras el usuario no tenia session.
  #esto me permite mandarlo a la misma pagina cuando se loguea
  before_filter :last_url_without_session

  def last_url_without_session
    if current_user.nil?
      session[:last_url_without_session] = request.request_uri
    end
  end

  def index
    # en caso de que el usuario este logueado se infieren algunos datos
    if !current_user.nil?
      params[:contact_us_email] = current_user.email
      if !current_user.contact.nil?
        contact = current_user.contact
        params[:contact_us_name] = "#{contact.first_name} #{contact.last_name}"
        params[:contact_us_phone] = contact.phone
        params[:contact_us_company] = ContactsHelper.get_customer_full_name contact
      end
    end
  end

  def validate_data
    error = false
    if params[:contact_us_name].nil? || params[:contact_us_name].strip.length() == 0
      error = true
      @name_error = t('contact_us.messages.field_null')
    end
    if params[:contact_us_email].nil? || params[:contact_us_email].strip.length() == 0
      error = true
      @email_error = t('contact_us.messages.field_null')
    else
      matches = params[:contact_us_email].match(Setting.validate_mail_regular_expresion)
      if matches.nil?
        error = true
        @email_error = t('contact_us.messages.email_invalid')
      end
    end

    if params[:contact_us_phone].nil? || params[:contact_us_phone].strip.length() == 0
      error = true
      @phone_error = t('contact_us.messages.field_null')
    end
    if params[:contact_us_text].nil? || params[:contact_us_text].strip.length() == 0
      error = true
      @text_error = t('contact_us.messages.field_null')
    end
    if params[:contact_us_subject].nil? || params[:contact_us_subject].strip.length() == 0
      error = true
      @subject_error = t('contact_us.messages.field_null')
    end

    if error
      render "index"
    end
  end

  def send_query
    Struct.new("ContactUsData", :name, :email, :phone, :company, :subject, :query, :ip_adress, :user_agent)
    data = Struct::ContactUsData.new(params[:contact_us_name], params[:contact_us_email], params[:contact_us_phone],
             params[:contact_us_company], params[:contact_us_subject], params[:contact_us_text],
             request.remote_ip, request.env["HTTP_USER_AGENT"])
    
    ApplicationMailer.deliver_contact_us(data)

    flash_message :notice, t('contact_us.messages.query_sent')
    redirect_to(root_path)
  end
end